<?php
class Default_Form_UsersForm extends Wlib_Form_Dojo_DojoBase
{
    protected $_cities = null;
    protected $_groups = null;
    protected $_userRoles = null;

    const PHONES_BLOCK_ELEMENT_ID = 'phones_block';

    public function setCities($cities)
    {
        $this->_cities = $cities;
        return $this;
    }

    public function getCities()
    {
        if(null === $this->_cities) {
            $cities = new Default_Model_DbMapper_Cities;
            $citiesList = $cities->getListWithOneFieldInRow();
            $this->_cities = $citiesList;
        }

        return $this->_cities;
    }

    public function setGroups($groups)
    {
        $this->_groups = $groups;
        return $this;
    }

    public function getGroups()
    {
        if(null === $this->_groups) {
            $groups = new Default_Model_DbMapper_StudentsGroups;
            $groupsList = $groups->getListWithOneFieldInRow();
            $this->_groups = $groupsList;
        }

        return $this->_groups;
    }

    public function setUserRoles($userRoles)
    {
        $this->_userRoles = $userRoles;
        return $this;
    }

    public function getUserRoles()
    {
        if(null === $this->_userRoles) {
            $usersDbMapper = new Default_Model_DbMapper_Users();
            $this->_userRoles = $usersDbMapper->getUserRoles();
        }
        return $this->_userRoles;
    }

    public function getBlocksMap()
    {
        $userRoles = $this->getUserRoles();

        $blocksMap = array();
        foreach ($userRoles as $roleId => $roleKeyword) {
            $blocksMap[$roleId] = 'fieldset-' . $roleKeyword;
        }

        return $blocksMap;
    }

    public function getEntitiesReqiredFields()
    {
        $entityRequiredFields = array(
            Default_Model_DbMapper_Users::USER_ROLE_STUDENT_ID => array('student_group_id', 'student_city_id'),
            Default_Model_DbMapper_Users::USER_ROLE_TEACHER_ID => array('teacher_group_ids'),
            Default_Model_DbMapper_Users::USER_ROLE_ACADEMIC_MANAGER_ID => array(),
            Default_Model_DbMapper_Users::USER_ROLE_ADMINISTRATIVE_MANAGER_ID => array(),
            Default_Model_DbMapper_Users::USER_ROLE_ADMINISTRATOR_ID => array()
        );

        return $entityRequiredFields;
    }

    public function isRequired($fieldName)
    {
        $entitysRequiredFieldList = $this->getEntitiesReqiredFields();
        $roleId = $this->getMetadataParam('roleId');

        if($roleId) {
            $entitysRequiredFieldList = array($roleId => $entitysRequiredFieldList[$roleId]);
        }

        foreach($entitysRequiredFieldList as $role => $fields) {
            if(in_array($fieldName, $fields)) {
                return true;
            }
        }

        return false;
    }

    public function init()
    {
        $this->setMethod('post');
        $this->setOptions(
            array('enctype' => 'multipart/form-data')
        );

        $this->addPrefixPath('Rzd_Form_Element_', 'Rzd/Form/Element/', 'element');

        $this->addElement(
            'ValidationTextBox',
            'last_name',
            array(
                'required' => true,
                'onchange' => 'rzd.users.generateLogin(this)'
            )
        );

        $this->addElement('ValidationTextBox', 'first_name', array('required' => true));
        $this->addElement('ValidationTextBox', 'second_name');
        $this->addElement('DateTextBox', 'birthday_date',
            array(
                'onclick' => '',
                'id' => 'test',
                'style' => 'width: 100px',
                'required' => true,
                'dropDownDefaultValue' => '10.02.1960'
        ));

        $login = $this->createElement(
            'userLogin',
            'login',
            array(
                'required' => true,
                'validators' => array(
                    array("Regex", false, array("/^[a-zA-Z0-9_-]+$/"))
                ),
                'userId' => $this->getMetadataParam('user_id')
            )
        );

        $excludParams = array('is_deleted' => '1');
        if($this->getMetadataParam('user_id')) {
            $excludParams['id'] = $this->getMetadataParam('user_id');
        }
        $noDbRecordExistsValidator = new Wlib_Validate_UniqueFieldValue(
            new Default_Model_DbTable_Users(), 'login', $excludParams
        );

        $login->addValidator($noDbRecordExistsValidator);
        $login->clearDecorators();
        $login->addDecorator('DijitElement')
            ->addDecorator('Errors')
            ->addDecorator('HtmlTag', array('tag' => 'div', 'id' => 'xzc'))
            ->addDecorator('Description', array('tag' => 'p', 'class' => 'description'))
            ->addDecorator('HtmlTag', array('tag' => 'dd', 'id' => 'userLoginWrapper'))
            ->addDecorator('Label', array('tag' => 'dt'));
        $this->addElement($login);

        $userPasswordValidate = new Rzd_Validate_UserPassword();

        $this->addElement('PasswordTextBox', 'password', array(
            'required' => false,
            'validators' => array(
                    array($userPasswordValidate, false, array())
             )
        ));

        $userPhotoElement = $this->createElement('file', 'photo',  array(
            'dojoType' => 'dojox.form.FileInput',
            'required' => false,
        ));

        $userPhotoElement->addPrefixPath('Wlib_Form_Decorator', 'Wlib/Form/Decorator/', 'decorator');

        $userPhotoElement->clearDecorators();
        $userPhotoElement->addDecorator('File')
            ->addDecorator('Errors')
            ->addDecorator('ViewImage', $this->getMetadataParam('imagePreviewOptions'))
            ->addDecorator('Description', array('tag' => 'p', 'class' => 'description'))
            ->addDecorator('HtmlTag', array('tag' => 'dd'))
            ->addDecorator('Label', array('tag' => 'dt'));

        $this->addElement($userPhotoElement);
        $this->addElement('ValidationTextBox', 'email', array('required' => true));

        $this->addElement('UserRole', 'role', array(
            'multiOptions' => array('' => '') + $this->getUserRoles(),
            'required' => true,
            'roleRequiredFields' => Zend_Json::encode($this->getEntitiesReqiredFields()),
            'blocksMap' => $this->getBlocksMap()
        ));

        $telephonesMultiDynamicValidator = new Rzd_Validate_RequiredFieldsInMultiDynamic(
            array(
                'requiredFields' => array(
                    'country_code',
                    'city_code',
                    'number',
                    'phone_type'
                ),
                'requiredFieldsName' => 'country_code, city_code, number, phone_type'
            )
        );
        $deleteEmptyValuesRowsFilter = new Rzd_Filter_DeleteEmptyValuesRows();
        $telephonesMultiDynamicElement = $this->createElement('TelephonesMultiDynamic', 'telephones');
        $telephonesMultiDynamicElement->addValidator($telephonesMultiDynamicValidator);
        $telephonesMultiDynamicElement->addFilter($deleteEmptyValuesRowsFilter);

        $this->addElement($telephonesMultiDynamicElement);

        $this->addDisplayGroup(
            array(
                'last_name',
                'first_name',
                'second_name',
                'birthday_date',
                'photo',
                'login',
                'password',
                'email',
                'role'
            ), 'general'
        );

        $this->addDisplayGroup(array('telephones'), 'contact_info');

        // --- student
        $studentEducationMultiDynamicValidator = new Rzd_Validate_RequiredFieldsInMultiDynamic(array(
                'requiredFields' => array(
                    'start_year',
                    'end_year',
                    'school',
                    'degree'
                ),
                'requiredFieldsName' => 'start_year, end_year, school, degree'
            )
        );
        $this->addElement('ValidationTextBox', 'student_company_name');
        $this->addElement('ValidationTextBox', 'student_department');
        $this->addElement('ValidationTextBox', 'student_position');

        $studentEducationMultiDynamic = $this->createElement(
            'StudentEducationMultiDynamic',
            'student_higher_education'
        );
        $studentEducationMultiDynamic->addValidator($studentEducationMultiDynamicValidator);
        $studentEducationMultiDynamic->addFilter($deleteEmptyValuesRowsFilter);

        $this->addElement($studentEducationMultiDynamic);

        $additionalEducationMultiDynamicValidator = new Rzd_Validate_RequiredFieldsInMultiDynamic(array(
                'requiredFields' => array(
                    'start_year',
                    'course_name',
                ),
                'requiredFieldsName' => 'start_year, course_name'
            )
        );
        $additionalEducationMultiDynamic = $this->createElement(
                'AdditionalEducationMultiDynamic',
                'student_additional_education'
        );
        $additionalEducationMultiDynamic->addValidator($additionalEducationMultiDynamicValidator);
        $additionalEducationMultiDynamic->addFilter($deleteEmptyValuesRowsFilter);

        $this->addElement($additionalEducationMultiDynamic);

        $this->addElement('FilteringSelect', 'student_group_id', array(
            'multiOptions' => array('' => '') + $this->getGroups(),
            'required' => $this->isRequired('student_group_id')
        ));
        $this->addElement('FilteringSelect', 'student_city_id', array(
            'multiOptions' => array('' => '') + $this->getCities(),
            'required' => $this->isRequired('student_city_id')
        ));

        $this->addDisplayGroup(
            array('student_company_name',
                'student_department',
                'student_position',
                'student_group_id',
                'student_city_id',
                'student_higher_education',
                'student_additional_education'
            ),
            Default_Model_DbMapper_Users::USER_ROLE_STUDENT_KEYWORD,
            array('class' => 'invisible')
        );


        // --- teacher
        $this->addElement('ValidationTextBox', 'teacher_degree',
            array('required' => $this->isRequired('teacher_degree')));
        $this->addElement('Editor', 'teacher_biography');

        $this->addElement(
            'MultiCheckbox',
            'teacher_group_ids',
            array(
                'multiOptions' => $this->getGroups(),
                'required' => $this->isRequired('teacher_group_ids')
            )
        );

        $this->addDisplayGroup(
            array(
                'teacher_degree',
                'teacher_biography',
                'teacher_group_ids'
             ),
            Default_Model_DbMapper_Users::USER_ROLE_TEACHER_KEYWORD,
            array('class' => 'invisible')
        );

        $this->addElement('SaveSubmit', 'save', array(
            'isEditMode' => $this->getMetadataParam('isEditMode'),
            'onclick' => 'return rzd.switchingRequiredFields("role",' . Zend_Json::encode($this->getBlocksMap()) . ')'
        ));

        foreach($this->getDisplayGroups() as $group) {
            $group->removeDecorator('DtDdWrapper');
        }
    }
}
